<template>
	<div class="box">
		<!-- 头部搜索模块 -->
		<headerSearch 
      :selectObj="selectObject" 
      :goSearchFc="searchClick" 
      :buttonList="buttonList"
    />
		<!-- 中间表格模块 -->
    <BaseTable
        :data="cargotableData"
        :columns="cargotableDataColumns"
        :tableHeight="mainHeight"
        :pagination="false"
        :loading="loading"
        @details="tableClick"
    ></BaseTable>

		<div class="page">
			<el-pagination
				background
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
				:current-page="queryAll.startpage"
				:page-sizes="[10, 15, 20, 25, 30]"
				:page-size="queryAll.pagesize"
				layout="total, sizes, prev, pager, next, jumper"
				:total="totalNum"
			></el-pagination>
		</div>

		<!-- 货权转移 -->
		<el-drawer
			:before-close="handleClose"
			title="货权转移"
			:visible.sync="drawerInner"
			direction="rtl"
      @open="openDrawer"
			size="70%"
		>
      <cargoTransferDetail
        ref="cargoTransfer"
        :cargoOwnerData="cargoOwnerData"
        :cargoAgentData="cargoAgentData" 
        :cargoStatus="cargoStatus"
      />
			<div class="demo-drawer__footer">
				<el-button type="primary" @click="cargoTransferSave" size="mini" v-if="!this.cargoStatus">保 存</el-button>
        <el-button size="mini" @click="drawerInner = false">取消</el-button>
			</div>
		</el-drawer>

    

	</div>
</template>

<script>
import Utils from '@/libs/Utils.js'
import BaseTable from '@/components/BaseTable'
import api from '@/api/yardTally/cargoTransfer'
import publicapi from '@/api/public'
import headerSearch from '@/components/headerSearch'
import cargoTransferDetail from './cargoTransferDetail.vue'

export default {
  name: 'cargoTransfer', // 票货管理
  components: {
    BaseTable,
    headerSearch,
    cargoTransferDetail
  },
  data() {
    return {
      // 搜索框显示对象
      selectObject: [
        {
          name: '船名航次',
          type: 'select',
          modelName: 'shipvoyageId',
          selectData: [],
          selectLabel: 'shipvoyageName',
          selectValue: 'shipvoyageId'
        },
        {
          name: '源货主',
          type: 'select',
          modelName: 'cargoOwnerIdSource',
          selectData: [],
          selectLabel: 'customerName',
          selectValue: 'customerId'
        },
        {
          name: '源货代',
          type: 'select',
          modelName: 'cargoAgentIdSource',
          selectData: [],
          selectLabel: 'customerName',
          selectValue: 'customerId'
        },
        {
          name: '目标货主',
          type: 'select',
          modelName: 'cargoOwnerId',
          selectData: [],
          selectLabel: 'customerName',
          selectValue: 'customerId'
        },
        {
          name: '目标货代',
          type: 'select',
          modelName: 'cargoAgentId',
          selectData: [],
          selectLabel: 'customerName',
          selectValue: 'customerId'
        },
        {
          name: '货名',
          type: 'select',
          modelName: 'cargoCode',
          selectData: [],
          selectLabel: 'cargoName',
          selectValue: 'cargoCode'
        }
      ],
      // header的按钮list
      buttonList: [
        { label: '查看', type: 'primary', icon: 'el-icon-search', click: () => this.getCargoTransferDetail, disabled: true, permission: 'tallyManagement:cargoTransfer:detail' },
        { label: '货转', type: 'primary', icon: 'el-icon-right', click: () => this.addCargoTransfer, disabled: true, permission: 'tallyManagement:cargoTransfer:insert' },
        { label: '撤销', type: 'danger', icon: 'el-icon-refresh', click: () => this.deleteCargoTransfer, disabled: true, permission: 'tallyManagement:cargoTransfer:delete' }
      ],
      cargotableDataColumns: [ // table表头
        { prop: 'shipvoyageName', label: '船名航次' },
        { prop: 'cargoOwnerNameSource', label: '源货主', isShort: true },
        { prop: 'cargoAgentNameSource', label: '源货代', isShort: true },
        { prop: 'cargoOwnerName', label: '目标货主', isShort: true },
        { prop: 'cargoAgentName', label: '目标货代', isShort: true },
        { prop: 'cargoName', label: '货名' },
        { prop: 'statusName', label: '货转状态' },
        { prop: 'quantity', label: '货转件数' },
        { prop: 'ton', label: '货转重量' },
        { prop: 'volume', label: '货转体积' }
      ],
      cargotableData: [], // table数据
      shipVoyageData: [], // 船名航次数据
      compData: [], // 组织数据
      customerData: [], // 货主货代开征公司数据
      cargoOwnerData: [], // 货主数据
      cargoAgentData: [], // 货代数据
      issuingData: [], // 开征公司数据
      cargoData: [], // 货名数据
      drawerInner: false, // 货权转移
      cargoStatus: false, // 是新增还是查看货转明细，控制input框
      fileList: [], // 货转附件数据
      cargoQuery: false, // 货权查询
      cargoTransferData: [], // 货权查询数据
      addFormData: { 'companyId': '', 'companyName': '', 'shipvoyageName': '', 'cargoOwnerName': '', 'cargoAgentName': '', 'cargoName': '', 'tradeName': '', 'packingName': '', 'issuingCompanyName': '', 'shipvoyageId': '', 'cargoOwnerId': '', 'cargoAgentId': '', 'cargoCode': '', 'tradeType': '', 'packing': '', 'issuingCompanyId': '' }, // 新建表单初始form
      activeName: 'first',
      loading: false,
      clickRow: {},
      queryAll: {
        startpage: 1,
        pagesize: 10,
        shipvoyageId: '',
        cargoOwnerIdSource: '',
        cargoOwnerId: '',
        cargoCode: ''
      },
      totalNum: 0,
      openFile: false // 查看附件
    }
  },
  async activated() {
    this.getCustomer()
    this.getCargo()
    this.getShipvoyage()
  },
  props: {
    height: {
      type: Number
    },
    customerId: {
      type: String,
      default: ''
    }
  },
  computed: {
    mainHeight: function() {
      return this.height ? this.height : this.$store.state.tableHeight - 40
    },
    tableHeight: function() {
      return this.$store.state.tableHeight - 40
    }
  },
  methods: {
    // 获取货权转移list
    async getCargoTransfer() {
      await api
        .reqGetCargoTransfer(this.queryAll)
        .then(res => {
          this.buttonList[0].disabled = true
          this.buttonList[1].disabled = true
          this.buttonList[2].disabled = true
          this.cargotableData = res.data.data.pages
          this.queryAll.startpage = res.data.data.pageNum
          this.queryAll.pagesize = res.data.data.pageSize
          this.totalNum = res.data.data.totalNum
        })
        .catch(() => {})
    },
    /**
     * 表格点击事件，拿到row的id
     */
    tableClick(row) {
      console.log(row, 'row');
      this.clickRow = row
      if (this.clickRow.status !== 1) {
        this.buttonList[0].disabled = false
        this.buttonList[1].disabled = true
        this.buttonList[2].disabled = false
      } else {
        this.buttonList[0].disabled = true
        this.buttonList[1].disabled = false
        this.buttonList[2].disabled = true
      }
    },
    /**
     * 查看货转明细
     */
    async getCargoTransferDetail() {
      this.drawerInner = true
      this.cargoStatus = true
      const res = await api.reqGetCargoTransferRecord(this.clickRow.id)
      const res1 = await api.reqGetCargoTransferDetail(this.clickRow.id)

      this.$nextTick(() => {
        this.$refs.cargoTransfer.formData = res.data.data
        this.$refs.cargoTransfer.queryAll.cargoInfoId = res.data.data.cargoInfoIdSource
        this.$refs.cargoTransfer.queryAll.tally = res.data.data.tally
        this.$refs.cargoTransfer.fileList = res.data.data.mattachmentInfoList
        this.$refs.cargoTransfer.yph = this.clickRow.cargoOwnerName + '/' + this.clickRow.cargoAgentName + '/' + this.clickRow.cargoName + '/' + this.clickRow.tradeType + '/' + this.clickRow.shipvoyageName
        this.$refs.cargoTransfer.stackingPositionList = res1.data.data
        // 判断是否有操作列，如果没有就加上
        const result = this.$refs.cargoTransfer.stackingPositionListColumns.some(item => item.label === '操作')
        if (result) this.$refs.cargoTransfer.stackingPositionListColumns.pop()
      })
    },
    /**
     * 打开新增货转明细抽屉,调接口得到货转记录
     */
    async addCargoTransfer() {
      this.drawerInner = true
      this.cargoStatus = false
      const operationObj = {
        label: '操作',
        fixed: 'right',
        align: 'center',
        width: 150,
        render: (h, params) => {
          return h(
            'div',

            [

              h('el-button', {
                props: {
                  size: 'mini'
                },

                domProps: {
                  // 添加标签,使用自己引入的iconfont图标
                  // innerHTML: `<i class="iconfont icon-tubiao_liebiaoshanchu" style="color:#DA2821"></i> 删除`
                  innerHTML: `<span style='color:#F75E5E'><i class='iconfont icon-1-08'></i><span  style='padding-left:5px;'>删除</span></span>`
                },
                on: {
                  click: () => {
                    this.handleDelete(params.row)
                  }
                }
              })
            ]
          )
        }
      }

      const res = await api.reqGetCargoTransferRecord(this.clickRow.id)
      console.log(res, 'ressss');
      this.$nextTick(() => {
        this.$refs.cargoTransfer.formData = res.data.data
        this.$refs.cargoTransfer.queryAll.cargoInfoId = res.data.data.cargoInfoIdSource
        this.$refs.cargoTransfer.queryAll.tally = res.data.data.tally
        this.$refs.cargoTransfer.fileList = res.data.data.mattachmentInfoList
        // 将id和对应字段填进去
        this.$refs.cargoTransfer.yph = this.clickRow.cargoOwnerName + '/' + this.clickRow.cargoAgentName + '/' + this.clickRow.cargoName + '/' + this.clickRow.tradeType + '/' + this.clickRow.shipvoyageName
        // 判断是否有操作列，如果没有就加上
        const result = this.$refs.cargoTransfer.stackingPositionListColumns.some(item => item.label === '操作')
        if (!result) this.$refs.cargoTransfer.stackingPositionListColumns.push(operationObj)
      })
    },
    /**
     * 货转明细保存
     */
    async cargoTransferSave() {
      const params = JSON.parse(JSON.stringify(this.$refs.cargoTransfer.formData))
      params.cargoTransferItemList = JSON.parse(JSON.stringify(this.$refs.cargoTransfer.stackingPositionList))
      api.reqSaveCargo(params).then(res => {
        if (res.data.code === '0000') {
          this.drawerInner = false
          this.$message.success('添加货转明细成功')
          this.$refs.cargoTransfer.$refs.ruleForm.resetFields()
          this.getCargoTransfer()
        }
      })
    },
    /**
     * 删除货转明细
     */
    async deleteCargoTransfer() {
      this.$confirm('此操作将撤销货转明细, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        api.reqDeleteCargoTransferDetail(this.clickRow.id).then(res => {
          if (res.data.code === '0000') {
            this.$message({
              type: 'success',
              message: '撤销成功!'
            });
            this.getCargoTransfer()
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    /**
     * 货权查询中查看附件
     */
    viewFile(row) {
      this.openFile = true
      console.log(row, 'row');
      this.fileList = row.mattachmentInfoList
    },

    /**
     * 获取客户信息，货主货代开征公司
     */
    async getCustomer() {
      const res = await publicapi.getlistCustomer()
      this.customerData = res.data.data
      this.selectObject[1].selectData = this.customerData
      this.selectObject[2].selectData = this.customerData
      this.selectObject[3].selectData = this.customerData
      this.selectObject[4].selectData = this.customerData
      this.cargoOwnerData = this.customerData.map(item => {
        return { cargoOwnerName: item.customerName, cargoOwnerId: item.customerId }
      })
      this.cargoAgentData = this.customerData.map(item => {
        return { cargoAgentName: item.customerName, cargoAgentId: item.customerId }
      })
      this.issuingData = this.customerData.map(item => {
        return { issuingCompanyName: item.customerName, issuingCompanyId: item.customerId }
      })
    },
    /**
     * 获取货名信息
     */
    async getCargo() {
      const res = await publicapi.getListCargo()
      this.cargoData = res.data.data
      this.selectObject[5].selectData = this.cargoData
    },
    /**
     * 获取船名航次
     */
    async getShipvoyage() {
      const res = await publicapi.getListShipvoyage()
      this.shipVoyageData = res.data.data
      this.selectObject[0].selectData = this.shipVoyageData
    },
    searchClick(searchData) {
      console.log(searchData, 'searchData');
      this.queryAll.startpage = 1
      this.queryAll = Object.assign(this.queryAll, searchData)
      this.getCargoTransfer()
    },

    handleSizeChange(val) {
      this.queryAll.pagesize = val
      this.getCargoTransfer()
    },
    handleCurrentChange(val) {
      this.queryAll.startpage = val
      this.getCargoTransfer()
    },
    /**
     * 打开抽屉的回调,将对应抽屉的form表单清空
     */
    openDrawer() {
      if (this.drawerInner) { // 货权转移
        this.$nextTick(() => {
          this.$refs.cargoTransfer.$refs.ruleForm.resetFields()
          this.$refs.cargoTransfer.stackingPositionList = []
        })
      }
    },
    handleClose(done) {
      const oldV = []
      let newV = []
      if (this.cargoStatus) return // 查看情况无需控制
      if (this.drawerInner) {
        newV = this.$refs.cargoTransfer.stackingPositionList
      }
      if (!Utils.compareData(oldV, newV)) {
        this.$confirm('修改的数据未保存，是否关闭？')
          .then(_ => {
            done()
          })
          .catch(_ => {})
      } else {
        done()
      }
    }
  }
}
</script>

<style lang="less" scoped>
@import "../component/index.less";
.selectBox {
	justify-content: space-between;
	display: flex;
	background: #ffffff;
	border: 1px solid #e1e4eb;
	border-bottom: 0;
	border-left: none;
	height: 50px;
	position: relative;
	align-items: center;
	padding-left: 14px;
	padding-right: 20px;
}
.input_box {
	display: flex;
}
.page {
	background: #ffffff;
	text-align: right;
	border-radius: 0 0 4px 4px;
	padding: 5px 20px;
}
/deep/.el-tabs--border-card > .el-tabs__content {
	padding: 0 !important;
}
//抽屉底部样式
/deep/ .el-drawer__header {
	margin-bottom: 0;
	padding: 16px;
	border-bottom: 1px solid gainsboro;
}
.demo-drawer__footer {
	text-align: right;
	padding-right: 20px;
	border-top: 1px solid #c8cfde;
	background-color: #f5f7fa;
	position: absolute;
	bottom: 0;
	left: 0;
	right: 0;
	line-height: 50px;
}
.box {
	background: #ffffff;
	border: 1px solid #e1e4eb;
	border-radius: 4px 4px 0 0;
	border-top: none;
}
</style>
